package com.ljh.gmall.util;

import com.ljh.gmall.common.Constants;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author LJH
 * @date 2019/10/14 21:23
 */
public class PmsUploadUtil {


    public static String uploadImage(MultipartFile multipartFile) {

        String url = Constants.CommonField.URL.getValue();

        //配置fdfs的全局链接地址
        String file = PmsUploadUtil.class.getResource("/tracker.conf").getFile();

        try {
            ClientGlobal.init(file);
            TrackerClient trackerClient = new TrackerClient();

            //获得一个trackerServer的实例
            TrackerServer trackerServer = trackerClient.getConnection();

            //获得一个tracker获得一个Storage链接客户端
            StorageClient storageClient = new StorageClient(trackerServer, null);

            //获得上传文件二进制对象
            byte[] bytes = multipartFile.getBytes();

            //获取文件后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            int i = originalFilename.lastIndexOf(".");
            String extName = originalFilename.substring(i+1);


            String[] uploadInfos = storageClient.upload_file(bytes, extName, null);
            for (String s : uploadInfos) {
                url += "/" + s;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

        return url;

    }
}
